package org.rcy.framework.thrift.serializer;

import net.qiyuesuo.rpc.thrift.metadata.FieldValueMetaData;
import net.qiyuesuo.rpc.thrift.metadata.SetMetaData;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TSet;

import java.util.HashSet;
import java.util.Set;

public class SetSerializer implements Serializer{

	@Override
	public Object read(TProtocol iprot, FieldValueMetaData valueMetaData) throws TException {
		SetMetaData setMetaData = (SetMetaData) valueMetaData;
		
		TSet set = iprot.readSetBegin();
		Set<Object> success = new HashSet(set.size);
		for (int i = 0; i < set.size; i++) {
			Object element = ThriftSerializer.read(iprot, setMetaData.elemMetaData);
			success.add(element);
		}
		iprot.readSetEnd();
		return success;
	}

	@Override
	public void write(TProtocol oprot, FieldValueMetaData valueMetaData, Object value) throws TException {
		SetMetaData setMetaData = (SetMetaData) valueMetaData;
		FieldValueMetaData elemMetaData = setMetaData.elemMetaData;
		Set set = (Set)value;

		oprot.writeSetBegin(new TSet(elemMetaData.type, set.size()));
		for (Object object : set) {
			ThriftSerializer.write(oprot, elemMetaData, object);
		}
		oprot.writeSetEnd();
	}
}
